import { getToken, removeToken, setTime, setToken } from '@/utils/auth'
import { getDetailUserInfoById, getUserInfo, login } from '@/api/user'

export default {
  namespaced: true,
  state: {
    token: getToken(), // 获取初始的token
    userInfo: {} // 定义获取用户信息的对象
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = {
        ...userInfo
      }
    },
    // 移除个人信息的方法
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async fetchLogin(context, data) {
      const result = await login(data)
      context.commit('setToken', result)
      //  登录成功设置时间戳
      setTime()
    },
    // 获取用户信息的接口
    async fetchUserInfo(context) {
      const result = await getUserInfo()
      const detailResult = await getDetailUserInfoById(result.userId)
      // console.log(result)
      context.commit('setUserInfo', {
        ...result,
        ...detailResult
      })
    },
    logOut(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}
